import Vue from 'vue';
Date.prototype.format = function(fmt) { // author: meizz
  var o = {
    'M+': this.getMonth() + 1, // 月份
    'd+': this.getDate(), // 日
    'h+': this.getHours(), // 小时
    'm+': this.getMinutes(), // 分
    's+': this.getSeconds(), // 秒
    'q+': Math.floor((this.getMonth() + 3) / 3), // 季度
    'S': this.getMilliseconds()
    // 毫秒
  };
  if (/(y+)/.test(fmt))
    fmt = fmt.replace(RegExp.$1, (this.getFullYear() + '').substr(4 -
            RegExp.$1.length));
  for (var k in o)
    if (new RegExp('(' + k + ')').test(fmt))
      fmt = fmt.replace(RegExp.$1, (RegExp.$1.length == 1) ?
        (o[k]) :
        (('00' + o[k]).substr(('' + o[k]).length)));
  return fmt;
};

var ComsUtil = {};
if (typeof require.context === 'undefined') {
  const fs = require('fs');
  const path = require('path');

  require.context = (base = '.', scanSubDirectories = false, regularExpression = /\.js$/) => {
    const files = {};

    function readDirectory(directory) {
      fs.readdirSync(directory).forEach((file) => {
        const fullPath = path.resolve(directory, file);

        if (fs.statSync(fullPath).isDirectory()) {
          if (scanSubDirectories) readDirectory(fullPath);

          return;
        }

        if (!regularExpression.test(fullPath)) return;

        files[fullPath] = true;
      });
    }

    readDirectory(path.resolve(__dirname, base));

    function Module(file) {
      return require(file);
    }

    Module.keys = () => Object.keys(files);

    return Module;
  };
}

function __createLink(src, id, callback) {
  let link = document.getElementById('#' + id);
  if (!document.getElementById('#' + id)) {
    link = document.createElement('link');
    link.id = id;
    link.rel = 'stylesheet';
    link.type = 'text/css';
    link.href = src;
    link.onload = function linkLoad() {
      if (callback) {
        callback();
      }
    }
    link.onerror = function linkError() {
      if (callback) {
        callback();
      }
    }
    document.head.appendChild(link);
  } else {
    link.href = src;
  }

}

ComsUtil.remoteRequire = function(list) {
  var d = [{
    'id': 28,
    'menuName': '菜单管理',
    'parentId': 0,
    'sortIndex': 1,
    'path': 'MenuManage',
    'componentCss': 'MenuManage.css',
    'componentFile': 'MenuManage.umd.js',
    'component': '/api/static/lib/MenuManage/',
    'menuType': 'L',
    'icon': '',
    'children': [],
    'file': null,
    'cssFile': null,
    'frame': false
  }];
  const modules = {};
  list.forEach(e => {
    switch (e.menuType) {
    case 'M':
      try {
        let css = require(`../${e.componentCss}`);
        let mo = require(`../${e.component}`);
        modules[e.path] = mo.default || mo;
        Vue.component(e.path, modules[e.path]);
      } catch (err) {
        console.error(e.path, e.component, err)
      }

      break;
    case 'L':
      Vue.component(e.path, function(resolve, reject) {
        // 异步加载模块如果使用同步的话modules可用
        var XML = new XMLHttpRequest();
        XML.open('GET', e.component + e.componentFile, false);
        XML.send();
        if (XML.status == 200) {
          // 执行以下js 字符串
          modules[e.path] = new Function(XML.responseText)();
          __createLink(e.component + e.componentCss, e.path);
          // 重点注意一下resolve
          // window[e.path]
          resolve(global[e.path])
        }
      });
      break;
    }
  });

  return modules;
}
ComsUtil.localRequire = function(data) {
  const modules = {};
  const files = require.context('../components/module/', true, /index.vue$/);
  var names = [];
  files.keys().forEach(key => {
    console.info('文件真实路径:', key)
    let pathArry = key.split('/');
    let name='';
    if (pathArry.length>3) {
      let ns =[];
      for (let i = 1; i < pathArry.length-1; i++) {
        ns.push(pathArry[i]);
      }
      name=ns.join('/');
    } else {
      name = pathArry[1];
    }

    if (!name) return;
    names.push(name);
    const componentConfig = files(key);
    modules[name] = componentConfig.default || componentConfig;
    Vue.component(name, modules[name]);
  });
  console.log(
    '\x1B[32m%s\x1B[45m',
    'module模块key值:' + JSON.stringify(names)
  );
  return modules;
};

export default ComsUtil;
